package org.ytor.core.sysapi.user.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.ytor.common.anno.AutoLog;
import org.ytor.common.model.R;
import org.ytor.core.BaseController;
import org.ytor.core.querygen.WhereGenerator;
import org.ytor.core.sqlflow.Page;
import org.ytor.core.sqlflow.builder.support.WhereBuilder;
import org.ytor.core.sqlflow.executor.DMLResult;
import org.ytor.core.sysapi.depart.resp.SysDepartResp;
import org.ytor.core.sysapi.dict.model.SysDict;
import org.ytor.core.sysapi.login.req.CheckPasswordReq;
import org.ytor.core.sysapi.login.req.RefreshPasswordReq;
import org.ytor.core.sysapi.role.model.SysRole;
import org.ytor.core.sysapi.user.logic.SysUserLogic;
import org.ytor.core.sysapi.user.model.SysUser;
import org.ytor.core.sysapi.user.repository.SysUserRepository;
import org.ytor.core.sysapi.user.req.SysUserReq;
import org.ytor.core.sysapi.user.resp.SysUserResp;
import org.ytor.core.sysapi.user.resp.SysUserRoleResp;

import java.util.List;

/**
 * created by   on 2025年4月9日 23:03:21
 * <br/>
 * User表控制器
 * <br/>
 */
@RestController
@RequestMapping("/rbac/user")
@Tag(name = "用户表")
public class SysUserController extends BaseController<SysUser, SysUserLogic, SysUserRepository> {

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "分页查询")
    public R<Page<SysUserResp>> page(@ParameterObject SysUserReq userdata,
                                     @RequestParam(defaultValue = "1") Integer pageNo,
                                     @RequestParam(defaultValue = "10") Integer pageSize) {
        WhereBuilder where = WhereGenerator.where();
        return R.success(logic.queryPage(pageNo, pageSize, where));
    }

    /**
     * 根据id查询数据
     */
    @GetMapping("/queryById")
    @Operation(summary = "根据id查询", description = "根据id查询数据")
    public R<SysUserResp> queryById(String id) {
        SysUser sysUser = repository.queryById(id);
        SysUserResp resp = null;
        if (sysUser != null) {
            resp = sysUser.toResp();
        }
        return R.success(resp);
    }

    /**
     * 新增或编辑数据
     */
    @AutoLog("新增或编辑数据")
    @PostMapping("/addOrUpdate")
    @Operation(summary = "新增或编辑", description = "根据有无主键id,新增或编辑数据")
    public R<String> addOrUpdate(@RequestBody SysUserReq userdata) {
        logic.addOrUpdate(userdata);
        return R.success(userdata.getId() == null ? "新增成功" : "编辑成功");
    }

    /**
     * 修改用户状态
     */
    @AutoLog("修改用户状态")
    @GetMapping("/status")
    @Operation(summary = "修改用户状态", description = "修改用户状态")
    public String addOrUpdate(@RequestParam String id, @RequestParam Integer status) {
        repository.update()
                .set(SysUser::getStatus, status)
                .where(w -> w.eq(SysUser::getId, id))
                .submit();
        return "修改成功";
    }

    /**
     * 删除
     */
    @AutoLog("根据id删除数据")
    @DeleteMapping("/delete/{ids}")
    @Operation(summary = "删除", description = "根据id删除数据")
    public R<String> delete(@PathVariable("ids") String ids) {
        logic.deleteByIds(ids);
        return R.success("删除成功");
    }


    /**
     * 查询用户角色信息
     */
    @GetMapping("/listUserRoles")
    @Operation(summary = "查询用户角色信息", description = "查询用户的角色信息")
    public List<SysUserRoleResp> listUserRoles(@RequestParam String userId, String roleName, String roleCode, String departIds) {
        return logic.listUserRoles(userId, roleName, roleCode, departIds);
    }

    /**
     * 修改用户角色信息
     */
    @GetMapping("/updateUserRole")
    @Operation(summary = "修改用户角色信息", description = "修改用户角色信息")
    public R<String> updateUserRole(@RequestParam String userId, @RequestParam String roleId) {
        logic.updateUserRole(userId, roleId);
        return R.success("操作成功");
    }

    /**
     * 查询用户所有部门信息
     */
    @GetMapping("/listUserAllDeparts")
    @Operation(summary = "查询用户所有部门信息", description = "查询用户所有部门信息")
    public List<SysDepartResp> listUserAllDeparts(@RequestParam String userId) {
        return logic.listUserDeparts(userId);
    }

    /**
     * 修改用户当前部门信息
     */
    @GetMapping("/updateUserCurrentDepart")
    @Operation(summary = "修改用户当前部门信息", description = "修改用户当前部门信息")
    public String updateUserCurrentDepart(@RequestParam String userId, @RequestParam String departCode) {
        logic.updateUserCurrentDepart(userId, departCode);
        return "分配成功";
    }

    /**
     * 校验密码
     */
    @PostMapping("/checkPassword")
    @Operation(summary = "校验密码", description = "校验密码")
    public R<String> checkPassword(@RequestBody @Valid CheckPasswordReq checkPasswordReq) {
        return R.success().setData(logic.checkPassword(checkPasswordReq));
    }

    /**
     * 更新密码
     */
    @PostMapping("/refreshPassword")
    @Operation(summary = "更新密码", description = "更新密码")
    public String refreshPassword(@RequestBody @Valid RefreshPasswordReq refreshPasswordReq) {
        logic.refreshPassword(refreshPasswordReq);
        return "更新成功";
    }


    @GetMapping("/test")
    @Operation(summary = "test", description = "test")
    @Transactional(rollbackFor = Exception.class)
    public SysUser test() {
        List<SysRole> sysRoles = repository.listAllRoleByUserId("1");
        repository.test(13, "发", List.of("123", "456"));
        List<SysDict> dict = repository.dict();
        SysUser sysUser = new SysUser()
                .setPassword("123456")
                .setUserName("hahaha")
                .setRealName("哈哈哈")
                .setPhone("123456789");
        repository.insert(sysUser);
        System.out.println(sysUser);
        return sysUser;
    }

    @GetMapping("/test1")
    @Operation(summary = "test1", description = "test1")
    @Transactional(rollbackFor = Exception.class)
    public DMLResult test1() {
        DMLResult delete = repository.delete(w -> w.eq(SysUser::getUserName, "hahaha").like(SysUser::getPhone, "4567"));
        return delete;
    }
}